<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\LayoutRequest;
use App\Models\Application\Layout;
use App\Models\Entity\Column\Collist;
use App\Models\Operation\ContentTemplate;
use App\Repositories\Application\LayoutRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;

class LayoutController extends Controller
{
    use ModelForm;

    /** @var  LayoutRepository */
    private $layoutRepository;

    public function __construct(LayoutRepository $layoutRepo)
    {
        $this->layoutRepository = $layoutRepo;
    }

    /**
     * Display a listing of the Layout.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.layouts.index_header'));
            $content->description(__('application.layouts.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Layout.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.layouts.create_header'));
            $content->description(__('application.layouts.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Layout in storage.
     *
     * @param LayoutRequest $request
     *
     * @return Response
     */
    public function store(LayoutRequest $request)
    {
        $input                    = $request->all();
        $layoutData               = [];
        $layoutData['name']       = $input['name'];
        $layoutData['descrition'] = $input['descrition'];

        $layout     = $this->layoutRepository->create($layoutData);
        $layoutArea = $input['layoutarea'];

        $layoutId = $layout->id;
        // 布局保存成功后保存layouts布局信息
        $datas = [];
        foreach ($layoutArea as $key => $value) {
            $data = [];
            if ($value['_remove_'] != '1') {
                $data['layout_id'] = $layoutId;
                $data['name']      = $value['name'];
                $data['data_id']   = $value['data_id'];
                $data['data_type'] = $value['data_type'];
                $datas[]           = $data;
            }
        }

        $insertStatus = DB::table('layout_areas')->insert($datas);
        if (empty($insertStatus)) {
            Flash::error('区位数据插入失败');
            return redirect(route('application.layouts.index'));
        }
        Flash::success(__('application.layouts.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.layouts.index'));

    }

    /**
     * Display the specified Layout.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $layout = $this->layoutRepository->findWithoutFail($id);

        if (empty($layout)) {
            Flash::error(__('application.layouts.not_found'));

            return redirect(route('application.layouts.index'));
        }

        return view('application.layouts.show')->with('layout', $layout);

    }

    /**
     * Show the form for editing the specified Layout.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('application.layouts.edit_header'));
            $content->description(__('application.layouts.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Layout in storage.
     *
     * @param  int              $id
     * @param LayoutRequest $request
     *
     * @return Response
     */
    public function update($id, LayoutRequest $request)
    {
        $layout = $this->layoutRepository->findWithoutFail($id);

        if (empty($layout)) {
            Flash::error(__('application.layouts.not_found'));

            return redirect(route('application.layouts.index'));
        }
        $input                    = $request->all();
        $layoutData               = [];
        $layoutData['name']       = $input['name'];
        $layoutData['descrition'] = $input['descrition'];
        $layout                   = $this->layoutRepository->update($layoutData, $id);

        $layoutArea = $input['layoutarea'];
        // 布局保存成功后保存layouts布局信息
        $datas = [];
        foreach ($layoutArea as $key => $value) {
            $data = [];
            if ($value['_remove_'] != '1') {
                $data['layout_id'] = $id;
                $data['name']      = $value['name'];
                $data['data_id']   = $value['data_id'];
                $data['data_type'] = $value['data_type'];
                $datas[]           = $data;
            }
        }
        DB::beginTransaction();
        try {
            DB::table('layout_areas')->where('layout_id', $id)->delete();
            DB::table('layout_areas')->insert($datas);
            DB::commit();
        } catch (Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            throw $e;
        }
        Flash::success(__('application.layouts.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.layouts.index'));
    }

    /**
     * Remove the specified Layout from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->layoutRepository->batchDelete('id', $id)) {
                // 删除布局相关的区位信息
                DB::table('layout_areas')->whereIn('layout_id', $layoutId)->delete();
                return response()->json(['message' => __('application.layouts.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $layout = $this->layoutRepository->findWithoutFail($id);

        if (empty($layout)) {
            Flash::error(__('application.layouts.not_found'));

            return redirect(route('application.layouts.index'));
        }

        if ($flag = $this->layoutRepository->delete($id)) {
            DB::table('layout_areas')->where('layout_id', $id)->delete();
            return response()->json(['message' => __('application.layouts.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Layout::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '布局名称');
            $form->textarea('descrition', '布局描述')
            ;
            // layout布局
            $form->hasMany('layoutarea', 'layout布局', function (Form\NestedForm $form) {
                $contentTemplates = ContentTemplate::pluck('alias as name', 'id')->toArray();
                // 模板推荐类型
                $dataTypes = [
                    0 => 'areaTpl',
                    1 => 'list0',
                    2 => 'topBanner',
                ];
                $form->text('name', 'area名称');
                // 数据类型
                $form->select('data_type', '数据类型')->options($dataTypes)->load('data_id', route('application.layouts.data_types.datas'), 'id', 'name');
                $form->select('data_id', '选择模板或数据')->options($contentTemplates);
            })->rules("required");
            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Layout::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('application.layouts.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.layouts.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.layouts.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.layouts.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('application.layouts.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('application.layouts.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('application.layouts.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.layouts.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('application.layouts.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.layouts.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '布局名称')->sortable();
            $grid->column('descrition', '布局描述')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '布局名称');

            });
        });
    }

    /**
     * 根据数据类型获取相关和数据
     * @return {[type]} [description]
     */
    public function getDataByDataType(Request $request)
    {
        $dataTypeId = $request->get('q');
        $data       = [];

        //  如果推荐模板类型为0, 则获取模板相关数据
        if ($dataTypeId === '0') {
            $data = ContentTemplate::orderBy('listorder', 'asc')->get(['alias as name', 'id'])->toArray();
            // 如果推荐模板类型为1, 则获取栏目列表数据
        } elseif ($dataTypeId === '1') {
            $data = Collist::orderBy('listorder', 'asc')->get(['name', 'id'])->toArray();
        } elseif ($dataTypeId === '2') {
            $data = [
                [
                    'id'   => 1,
                    'name' => 'topBanner模板数据',
                ],
                [
                    'id'   => 2,
                    'name' => 'topBanner模板数据',
                ],
                [
                    'id'   => 3,
                    'name' => 'topBanner模板数据',
                ],
            ];
        }
        return array_merge([['id' => '', 'name' => '选择']], $data);
    }
}
